package org.bbelovic.devel.pexeso.gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * Dialog for adding new players to Pairs game. This dialog is modal by default.
 */
public class AddPlayerDialog extends JDialog {

    private static final long serialVersionUID = 8496895295005110354L;

    private static final int DIALOG_WIDTH = 400;
    private static final int DIALOG_HEIGHT = 100;

    private static final String DIALOG_TITLE = "Add new player";

    private final JTextField playerNameField = new JTextField(30);
    private final JButton addPlayer = new JButton("Add player");
    private final JButton quitDialog = new JButton("Done adding players");
    private final Frame parentFrame;

    /**
     * Constructs new dialog.
     * @param parentFrame parent frame
     */
    public AddPlayerDialog(final Frame parentFrame) {
        super(parentFrame, true);
        this.parentFrame = parentFrame;
        initUI();
    }

    /**
     * Sets up user interface and register all listeners to their components.
     */
    private void initUI() {
        // set up UI
        setTitle(DIALOG_TITLE);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        setLayout(new FlowLayout());
        add(playerNameField);
        add(addPlayer);
        add(quitDialog);

        // register listeners
        quitDialog.addActionListener(new QuitDialogActionListener());
        addPlayer.addActionListener(new AddPlayerActionListener());
        
        setResizable(false);
        setVisible(true);
    }

    // listener inner classes

    /**
     * {@link ActionListener} for adding new {@link Player} to game. This listener will
     * register player with {@link GameListener} and will also add label to player
     * information panel on main screen. 
     */
    private class AddPlayerActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent evt) {
            final String playerName = playerNameField.getText();
            if (Utilities.notEmpty(playerName)) {
                final Player player = new Player(playerName);
                parentFrame.addPlayerLabel(player);
                playerNameField.setText("");
            } else {
                Utilities.showErrorMessage("Invalid name", "Player's name can not be empty!");
            }
        }
    } // AddPlayerActionListener class

    /**
     * {@link ActionListener} for closing dialog window.
     */
    private class QuitDialogActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    } // QuitDialogActionListener class

}
